#include "screen_helper.h"
#if defined(HAS_QNX_SCREEN) && HAS_QNX_SCREEN
#include <string.h>
#include <errno.h>

#define LOGD printf
#define LOGE printf

int SetDisplayId(screen_context_t ctx, screen_window_t win, int32_t displayId)
{
    int32_t displayCnt = 0;
    screen_get_context_property_iv(ctx, SCREEN_PROPERTY_DISPLAY_COUNT, &displayCnt);
    //LOGD("we have display count: %d\n", displayCnt);
    if (displayCnt > displayId)
    {
        screen_display_t  screen_dpy[DISPLAY_MAX_ID] = {0};
        int rc = screen_get_context_property_pv(ctx, SCREEN_PROPERTY_DISPLAYS, (void **)screen_dpy);   

        if (rc != 0)
        {
            return rc;
        }

        return screen_set_window_property_pv(win, SCREEN_PROPERTY_DISPLAY, (void **)&screen_dpy[displayId]);
    }

    return -1;
}



int SetWindowIVs(screen_window_t win, int32_t ivs[])
{

    int32_t* piv = ivs;
    int rc;
    while(*piv != WIN_IV_END)
    {
        /** todo refine me */
        rc = screen_set_window_property_iv(win, *piv, piv+2); /**piv+2, skip property and val count */

        if (rc != 0)
        {
            LOGE("set window property(%d) failed(%s)\n", *piv, strerror(errno));
            return rc;
        }
        piv += *(piv+1) + 2; /** *(piv+1): vals, 2: property and val count */
    }

    return 0;
}


int SetBufferIVs(screen_buffer_t sbuf, int32_t ivs[])
{
    int32_t* piv = ivs;
    int rc;
    while(*piv != WIN_IV_END)
    {
        /** todo refine me */
        int rc = screen_set_buffer_property_iv(sbuf, *piv, piv+2); /**piv+2, skip property and val count */
        if (rc != 0)
        {
            return rc;
        }
        piv += *(piv+1) + 2; /** *(piv+1): vals, 2: property and val count */
    }

    return 0; 
}

int CreateWindow(screen_context_t ctx, screen_window_t& win, int32_t display_id, int ivs[])
{
    if (!ivs)
    {
        LOGE("bad parameter\n");
        return -1;
    }
    
    LOGD("[%s.%d]===>:\n", __FUNCTION__, __LINE__);
    int rc = screen_create_window(&win, ctx); 

    if (rc != 0)
    {
        LOGE("create window failed(%s)\n", strerror(errno));
        return rc;
    }

    LOGD("[%s.%d]===>:\n", __FUNCTION__, __LINE__);

    rc = SetDisplayId(ctx, win, display_id);

    if (rc != 0)
    {
        LOGE("set display ID failed(%s)\n", strerror(errno));
        return rc;
    }

    LOGD("[%s.%d]===>:\n", __FUNCTION__, __LINE__);

    return SetWindowIVs(win, ivs);        
}

#endif /** end of HAS_QNX_SCREEN */

